package com.bhs.sansong.ui.main;

import static com.bhs.sansong.utils.VoiceUtils.newOrder;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import androidx.viewpager2.widget.ViewPager2;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.graphics.Color;
import android.os.IBinder;
import android.util.Log;
import android.view.MenuItem;

import com.bhs.sansong.R;
import com.bhs.sansong.base.BaseActivity;
import com.bhs.sansong.base.MyApplication;

import com.bhs.sansong.bean.AdvancePayment;
import com.bhs.sansong.bean.NewMessage;
import com.bhs.sansong.bean.NewNotice;
import com.bhs.sansong.bean.Permission;
import com.bhs.sansong.bean.SocketBean;
import com.bhs.sansong.net.JWebSocketClient;
import com.bhs.sansong.net.NetCallBack;
import com.bhs.sansong.serve.JWebSocketClientService;

import com.bhs.sansong.utils.LogUtils;
import com.bhs.sansong.utils.StatusBarUtil;
import com.bhs.sansong.utils.ToastUtil;

import com.bhs.sansong.utils.VersionUpdatingUtils;
import com.google.android.material.badge.BadgeDrawable;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.android.material.navigation.NavigationBarView;
import com.google.gson.Gson;
import com.umeng.analytics.MobclickAgent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.List;

import okhttp3.ResponseBody;
import pub.devrel.easypermissions.EasyPermissions;
import retrofit2.Response;

public class MainActivity extends BaseActivity implements EasyPermissions.PermissionCallbacks, NetCallBack {

    private ViewPager2 viewPage;
    private BottomNavigationView navView;
    private JWebSocketClient client;
    private JWebSocketClientService.JWebSocketClientBinder binder;
    private JWebSocketClientService jWebSClientService;
    private ChatMessageReceiver chatMessageReceiver;

    private BadgeDrawable badge;
    private int mPosition;
    @Override
    public int initLayout() {
        return R.layout.activity_main;
    }

    @Override
    public void initView() {
        //注册监听
        EventBus.getDefault().register(this);
        StatusBarUtil.setTranslucentStatus(this, true);
        if (!StatusBarUtil.setStatusBarDarkTheme(this, true)) {
            StatusBarUtil.setStatusBarColor(this, 0x55000000);
        }
        viewPage = findViewById(R.id.view_page);
        navView = findViewById(R.id.nav_view);
        navView.setItemIconTintList(null);
        //蒲公英版本更新
        VersionUpdatingUtils.versionUpdating(mActivity,1);
        bindService();
        doRegisterReceiver();
    }


    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {

    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
    }


    @Override
    public void onResponse(int requestCode, String json, Response<ResponseBody> response) throws Exception {
        AdvancePayment payment=new Gson().fromJson(json,AdvancePayment.class);
        if(payment.isStatus()){
            if (Integer.parseInt(payment.getData().getNum()) > 0) {
                EventBus.getDefault().postSticky(new NewMessage("quanzi","666"));
                messageRed();
            }
        }
    }

    @Override
    public void onFailure(int requestCode) {

    }


    /**
     * 广播消息 长连接消息
     */
    private class ChatMessageReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String message = intent.getStringExtra("message");
            LogUtils.d(message);
            SocketBean socketBean = new Gson().fromJson(message, SocketBean.class);
            if (socketBean.getType().equals("new_circle")) {
                messageRed();
                EventBus.getDefault().postSticky(new NewMessage("quanzi","666"));
            }else if(socketBean.getType().equals("order_rob_result")){
                newOrder(mActivity);
            }
        }
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
        EventBus.getDefault().post(new Permission());
    }

    /**
     * 动态注册广播
     */
    private void doRegisterReceiver() {
        chatMessageReceiver = new ChatMessageReceiver();
        IntentFilter filter = new IntentFilter("com.xch.servicecallback.content");
        registerReceiver(chatMessageReceiver, filter);
    }

    /**
     * 绑定服务
     */
    private void bindService() {
        Intent bindIntent = new Intent(MainActivity.this, JWebSocketClientService.class);
        bindService(bindIntent, serviceConnection, BIND_AUTO_CREATE);
    }

    private ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            //服务与活动成功绑定
            Log.e("hello", "服务与活动成功绑定");
            binder = (JWebSocketClientService.JWebSocketClientBinder) iBinder;
            jWebSClientService = binder.getService();
            client = jWebSClientService.client;
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            //服务与活动断开
            Log.e("hello", "服务与活动成功断开");
        }
    };


    @Override
    public void initData() {
        viewPage.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                navView.getMenu().getItem(position).setChecked(true);
            }
        });
        //禁止滑动
        viewPage.setUserInputEnabled(false);
        viewPage.setOffscreenPageLimit(4);//预加载四个 避免fragment销毁，重复创建
        viewPage.setAdapter(new FragmentAdapter(this));
        viewPage.setCurrentItem(0, false);
        navView.setOnItemSelectedListener(new NavigationBarView.OnItemSelectedListener() {
            @SuppressLint("NonConstantResourceId")
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                // 跳转指定页面：Fragment
                switch (item.getItemId()) {
                    case R.id.navigation_order_goods:
                        viewPage.setCurrentItem(1, false);
                        break;
                    case R.id.navigation_san_song:
                        viewPage.setCurrentItem(0, false);
                        break;
                    case R.id.navigation_message:
                        if (badge != null) {
                            badge.setVisible(false);
                        }
                        viewPage.setCurrentItem(2, false);
                        break;
                    case R.id.navigation_mine:
                        viewPage.setCurrentItem(3, false);
                        break;

                }
                return false;
            }
        });
        networkRequest(netApi.get_new_circle_num(), this);
    }

    static class FragmentAdapter extends FragmentStateAdapter {
        public FragmentAdapter(@NonNull FragmentActivity fragmentActivity) {
            super(fragmentActivity);
        }

        @NonNull
        @Override
        public Fragment createFragment(int position) {
            switch (position) {
                case 0:
                    return SanSongFragment.newInstance();
                case 1:
                    return OrderGoodsFragment.newInstance();
                case 2:
                    return MessageFragment.newInstance();
                default:
                    return MineFragment.newInstance();

            }
        }

        @Override
        public int getItemCount() {
            return 4;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        jWebSClientService = null;
        unbindService(serviceConnection);
        unregisterReceiver(chatMessageReceiver);
        closeConnect();
    }

    //新通知给个小红点
    @Subscribe
    public void onEvent(NewNotice event) {
        messageRed();
    }

    //新消息给个小红点
    @Subscribe
    public void onEvent(NewMessage event) {
        messageRed();
    }

    private void messageRed() {
        if (mPosition != 2) {
            if (badge == null) {
                badge = navView.getOrCreateBadge(R.id.navigation_message);
                badge.setBackgroundColor(Color.parseColor("#FF6067"));
            } else {
                badge.setVisible(true);
            }
        }
    }

    /**
     * 断开连接
     */
    private void closeConnect() {
        try {
            if (null != client) {
                client.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            client = null;
        }
    }


    private long exitTime;

    @Override
    public void onBackPressed() {
        if ((System.currentTimeMillis() - exitTime) > 2000) {
            ToastUtil.show("再按一次退出程序");
            exitTime = System.currentTimeMillis();
        } else {
            MobclickAgent.onKillProcess(MyApplication.getContext());
            finish();
        }
    }

}